// Gauge.cpp : Defines the entry point for the DLL application.
//

#include "stdafx.h"
#include "Gauge.h"
#include "../Infobus/Infobus.h"
#include "../Infobus/Types.h"
#include "../Infobus/XmlHelper.h"
#include "../Infobus/DatabaseAdapter.h"
#include "../Infobus/EventHandler.h"
#include <sstream>

void Gauge::onMessage(const char * m)
{
  if (m) {
    std::stringstream ss;
    ss << m << std::endl;

    EventHandler * pEvthnd = new EventHandler;
    EventScheme * pEvtSch = NULL;
    
    pEvthnd->SelectTraceLine(_bstr_t(m), &pEvtSch);
    if (!pEvtSch) return;

    pEvthnd->SearchEventMetaData(pEvtSch->getExecutable(), pEvtSch->getClassName(), pEvtSch->getMethodName(), &pEvtSch);
    pEvthnd->StoreEventScheme(pEvtSch);
       
    if (pEvtSch->getSequence() == pEvtSch->getSequenceSize())
    {
      bool bDispatch = false;
      if (1 == pEvtSch->getSequence()) {  
        bDispatch = true;
      } else {
        long lSeqSize = pEvtSch->getSequenceSize();
        long seqstored = 0;
        if (lSeqSize == (seqstored = pEvthnd->SequenceCount(pEvtSch))) {
          bDispatch = true;
        }
      }
      if (true == bDispatch) {
        pEvthnd->SelectFullPattern(&pEvtSch);
        pEvthnd->SelectFullTrace(&pEvtSch);
        pDisp->sendMessage(pEvtSch->toXml());
        pEvthnd->SetEventSchemeStatus(DELIVERED, pEvtSch);
      }
    }    
    if (pEvtSch) delete pEvtSch;
    if (pEvthnd) delete pEvthnd;
  }
}

Gauge::Gauge()
: IListener(TRACES)
, pDisp(NULL)
{
  this->setAliveBeats(true);
  pDisp = new Dispatcher(EVENTS);
  pDisp->setAliveBeats(false);
}

Gauge::~Gauge()
{
  if (pDisp) delete pDisp;
}
